#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from fastapi import APIRouter
from datetime import timedelta, datetime, timezone

from common.result import Success, Fail
from settings import JwtConfig
from app.admin.schema.login import (
    FetchTokenSchema, PayLoad, TokenBack
)
from app.admin.service import LoginService, UserService

router = APIRouter()

@router.post("/access-token", summary="获取token")
async def fetch_access_token(
    obj_in: FetchTokenSchema
):
    db_user = await UserService.authenticate(
        username=obj_in.username,
        password=obj_in.password
    )
    if not db_user:
        return Fail(code=400, msg="无效的用户名或密码")
    if db_user.status == 1:
        return Fail(code=400, msg="用户被禁用")
    expire = datetime.now(timezone.utc) + timedelta(minutes=JwtConfig.JWT_EXPIRE_MINUTES)
    token = await LoginService.create_access_token(
        payload=PayLoad(
            user_id=db_user.id,
            exp=expire
        )
    )
    res = TokenBack(access_token=token)
    return Success(data=res.model_dump())